package com.mark.common.utils;

import com.mark.common.exception.Campuso2oException;
import com.mark.web.data.exception.FileUtilException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Path;

/**
 * @Description:  将上传的文件通过类型装换的方式保存到本地服务器
 * @Author: Mark
 * @CreateDate: 2019/6/2 13:38
 * @Version: 2.0
 * @Copyright : 豆浆油条个人非正式工作室
 */
@Slf4j
public class UploadFileUtil {

    private UploadFileUtil(){}

    /**
     *
     * @param uploadFile
     * @param moduleBasePath
     * @return
     */
    public static String uploadFileToLocal(MultipartFile uploadFile,String moduleBasePath){
        //参数校验
        if(null == uploadFile){
            throw new Campuso2oException("上传的文件不能为空！");
        }
        if(StringUtils.isBlank(uploadFile.getOriginalFilename())){
            throw new Campuso2oException("上传的文件的原始文件名不能为空！");
        }

        String newFileName = ImageUtil.getNewFileName(uploadFile.getOriginalFilename());
        StringBuilder saveToLocalPath = new StringBuilder(moduleBasePath);

        if(!moduleBasePath.endsWith(PathUtil.separator)){
            saveToLocalPath.append(PathUtil.separator);
        }
        saveToLocalPath.append(newFileName);

        //检查存储文件的base路径是否存在，不存在则新建
        try {
            File file = new File(moduleBasePath);
            //如果moduleBasePath路径不存在，则建立该路径
            if (!file.exists()) {
                boolean writable = file.setWritable(true);
                boolean mkdirsRes = file.mkdirs();
                if(!writable || !mkdirsRes ){
                    log.error("自动生成目标文件路径"+moduleBasePath+"失败！请检查服务器中是否存在该目录！");
                }
            }
        }catch (Exception e){
            throw new FileUtilException("生成目标文件路径:" + moduleBasePath + "异常" + e.getMessage());
        }

        File localFile = new File(saveToLocalPath.toString());

        //将MultipartFile写到本地文件中
        try {
            uploadFile.transferTo(localFile);
        } catch (IOException e) {
            throw new FileUtilException("MultipartFile文件装换为File文件异常："+e.getMessage());
        }

        //返回相对路径
        String basePath = PathUtil.getImageBasePath();
        return saveToLocalPath.toString().replace(basePath, StringUtils.EMPTY);
    }


}
